#!/bin/bash

. /lib/lsb/init-functions
#Service specific variables
SHORT_NAME=simple-lookup-service
LONG_NAME="Simple Lookup Service"
VERSION="0.1"

#LS variables
HOME_PREFIX=/etc/opt/$SHORT_NAME
DIST_PREFIX=/opt/$SHORT_NAME
BINDIR=$DIST_PREFIX/bin
QDATADIR=$DIST_PREFIX/data
CONFDIR=$HOME_PREFIX
RUNDIR=/var/run/$SHORT_NAME
LOGDIR=/var/log/$SHORT_NAME
LOCK_FILE=/var/lock/$SHORT_NAME
USER=lookup
GROUP=lookup
STOP_TIMEOUT=10
RESTART_DELAY=5
PIDFILE=$RUNDIR/$SHORT_NAME.pid
JARFILE=$DIST_PREFIX/target/$SHORT_NAME-server-$VERSION.one-jar.jar
LOOKUPSERVICE_CMD="$BINDIR/startServer.sh"
LOOKUPSERVICE_CMD_OPTION=" $PIDFILE $JARFILE -c $CONFDIR/ -l $CONFDIR/log4j.properties > $LOGDIR/$SHORT_NAME.out -d $QDATADIR 2>&1"

#functions
start(){
    echo -n $"Starting $SHORT_NAME: "
    start-stop-daemon --start --pidfile $PIDFILE --chuid $USER --background --exec $LOOKUPSERVICE_CMD -- $LOOKUPSERVICE_CMD_OPTION
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch $LOCK_FILE
    return $RETVAL
}

stop(){
    echo -n $"Stopping $SHORT_NAME: "
	start-stop-daemon --stop -p $PIDFILE
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && rm -f $LOCK_FILE $PIDFILE
}

#handle arguments
ERROR=0
ARGV="$@"
if [ -z "$ARGV" ] ; then 
    ARGS="help"
fi

for ARG in $@ $ARGS
do
    case $ARG in
    start)
        start
	;;
    stop)
	    stop
	;;
    restart)
    	stop
    	sleep $RESTART_DELAY
    	start
	;;
	status)
	    pidofproc -p $PIDFILE $SHORT_NAME
	;;
    *)
	echo "usage: $0 (start|stop|restart|help)"
	cat <<EOF

        start      - start $LONG_NAME
        stop       - stop $LONG_NAME
        restart    - restart $LONG_NAME if running by sending a SIGHUP or start if
             not running
        status     - status of $LONG_NAME
        help       - this screen

EOF
	ERROR=2
    ;;

    esac

done

exit $ERROR
